//
//  RegionSeletedViewController.m
//  JxCarios
//
//  Created by xcq on 15/2/17.
//  Copyright (c) 2015年 xiongchuanqi. All rights reserved.
//

#import "RegionSeletedViewController.h"
#import "ChineseInclude.h"
#import "PinYinForObjc.h"
#import "CarAroundDataSource.h"

typedef struct faceAboutData {
    CGFloat leftBj;
    CGFloat rightBj;
    CGFloat btnNj;
    CGFloat onTopJl;
    CGRect btnFrame; //按钮frame
    CGRect labelFrame; //提示框frame
    CGFloat heartCityViewHeight; //热门城市高
} face;

static BOOL searchState = NO;
static NSString *cellIdentifier = @"cell";

@interface RegionSeletedViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSMutableArray *searchResults;  //搜索数据源头
    NSMutableArray *dataArray;      //城市列表正常数据源
    NSMutableArray *heartCity;      //热门城市
    CarAroundDataSource *carAround;
    NSMutableArray *_key;
    NSMutableDictionary *cityDic;
}


@end

@implementation RegionSeletedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _currenPage = 1;
    _totalPage = @"0";
    [_currenLocation addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(currenLocation:)]];
    [self initAbout];
    [self netRequest];
}


- (void)netRequest {
 
    if (!carAround) {
        carAround = [CarAroundDataSource dataSourceWithRequestor:self];
    }
    
    [carAround getHotCity:^(id result) {
        carAround.page = INTCONVERSTR(_currenPage);
        [carAround getCityArr:^(id result) {
            cityDic = [NSMutableDictionary dictionaryWithDictionary:[result customObjectForkey:@"citylist"]];
            [self initDataSource];
        } anfFail:^(id result) {
            
        }];
        heartCity = [NSMutableArray arrayWithArray:[result customObjectForkey:@"hotcity"]];
        [self hotCityInit];
    } anfFail:^(id result) {
        
    }];
  
    //TODO:请求数据
}

- (void)hotCityInit {
    NSInteger hotCount = heartCity.count;
    _heartCity = [UIView new];
    int lever = 0;
    if (hotCount <= 3) {
        lever = 1;
    }else if (hotCount <= 6) {
        lever = 2;
    }else {
        lever = 3;
    }
    face faceRect;
    if ([RextExtends getScreenFrame].size.width == 320) {
        faceRect.leftBj = 15;
        faceRect.rightBj = 15;
        faceRect.btnNj = 10;
        faceRect.onTopJl = 5;
    }else if ([RextExtends getScreenFrame].size.width == 375) {
        faceRect.leftBj = 25;
        faceRect.rightBj = 24;
        faceRect.btnNj = 28;
        faceRect.onTopJl = 5;
    }else if ([RextExtends getScreenFrame].size.width == 414) {
        faceRect.leftBj = 30;
        faceRect.rightBj = 30;
        faceRect.btnNj = 42;
        faceRect.onTopJl = 5;
    }
    faceRect.btnFrame = CGRectMake(15, 23, 90, 29);
    faceRect.labelFrame = CGRectMake(15, 3, 72, 21);
    UILabel *label = [[UILabel alloc] initWithFrame:faceRect.labelFrame];
    [label setText:@"热门城市"];
    [label setFont:[UIFont systemFontOfSize:12.f]];
    [label setTextColor:[UIColor lightGrayColor]];
    int y = 0;
    int z = 0;
    switch (lever) {
        case  1: //一排
        {
            CGRect heartRect = CGRectMake(0, 49, CGRectGetWidth([RextExtends getScreenFrame]), 8 + faceRect.btnFrame.size.height + faceRect.labelFrame.size.height + faceRect.labelFrame.origin.y);
            [self heartSet:heartRect andLabel:label];
            for (int i = 0; i < hotCount; i ++) {
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                     [btn setFrame:CGRectMake(faceRect.leftBj + (i * faceRect.btnFrame.size.width) + (i * faceRect.btnNj), faceRect.btnFrame.origin.y, CGRectGetWidth(faceRect.btnFrame), CGRectGetHeight(faceRect.btnFrame))];
             
                [self btnSet:btn andIndex:i];

            }
        }
            break;
        case 2://两排
        {
            CGRect heartRect = CGRectMake(0, 49, CGRectGetWidth([RextExtends getScreenFrame]), 8 +(2 * faceRect.btnFrame.size.height) + faceRect.onTopJl + faceRect.labelFrame.size.height + faceRect.labelFrame.origin.y);
            [self heartSet:heartRect andLabel:label];
            for (int i = 0; i < hotCount; i ++) {
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                [btn setFrame:CGRectMake(faceRect.leftBj + (i * faceRect.btnFrame.size.width) + (i * faceRect.btnNj), faceRect.btnFrame.origin.y, CGRectGetWidth(faceRect.btnFrame), CGRectGetHeight(faceRect.btnFrame))];
                if (i > 2) {
                    [btn setFrame:CGRectMake(faceRect.leftBj + (y * faceRect.btnFrame.size.width) + (y * faceRect.btnNj), faceRect.btnFrame.origin.y + faceRect.btnFrame.size.height + faceRect.onTopJl, CGRectGetWidth(faceRect.btnFrame), CGRectGetHeight(faceRect.btnFrame))];
                    y ++;
                }
                [self btnSet:btn andIndex:i];

            }
        }
            break;
        case 3://三排
        {
            CGRect heartRect = CGRectMake(0, 49, CGRectGetWidth([RextExtends getScreenFrame]), 8 +(3 * faceRect.btnFrame.size.height) + (2 * faceRect.onTopJl) + faceRect.labelFrame.size.height + faceRect.labelFrame.origin.y);
            [self heartSet:heartRect andLabel:label];
            for (int i = 0; i < hotCount; i ++) {
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
                [btn setFrame:CGRectMake(faceRect.leftBj + (i * faceRect.btnFrame.size.width) + (i * faceRect.btnNj), faceRect.btnFrame.origin.y, CGRectGetWidth(faceRect.btnFrame), CGRectGetHeight(faceRect.btnFrame))];
                if (i > 2) {
                    [btn setFrame:CGRectMake(faceRect.leftBj + (y * faceRect.btnFrame.size.width) + (y * faceRect.btnNj), faceRect.btnFrame.origin.y + faceRect.btnFrame.size.height + faceRect.onTopJl, CGRectGetWidth(faceRect.btnFrame), CGRectGetHeight(faceRect.btnFrame))];
                    y ++;
                }
                if (i > 5) {
                    [btn setFrame:CGRectMake(faceRect.leftBj + (z * faceRect.btnFrame.size.width) + (z * faceRect.btnNj), faceRect.btnFrame.origin.y + 2 * (faceRect.btnFrame.size.height + faceRect.onTopJl), CGRectGetWidth(faceRect.btnFrame), CGRectGetHeight(faceRect.btnFrame))];
                    z ++;
                }
                [self btnSet:btn andIndex:i];
            }
        }
            break;
    }
    [self.view addSubview:_heartCity];
    
   
}

- (void)heartSet:(CGRect)heartRect andLabel:(UILabel *)label{
    _heartCity = [[UIView alloc] initWithFrame:heartRect];
    _heartCity.backgroundColor = UICOLOR_MAKE_RGB(235, 235, 241);
    [_heartCity addSubview:label];
}

- (void)btnSet:(UIButton *)btn andIndex:(int)i{
     [btn setTag:200+i];
    [btn addTarget:self action:@selector(hotCityBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundColor:UICOLOR_MAKE_RGB(131, 181, 247)];
    [btn setTitle:[[heartCity objectAtIndex:i] customObjectForkey:@"NAME"] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn.titleLabel setTextAlignment:NSTextAlignmentLeft];
//    btn.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    NSLog(@"btn.title:%@",btn.titleLabel.text);
    NSLog(@"btn.frame :%@",NSStringFromCGRect(btn.frame));
    [_heartCity addSubview:btn];
}

- (void)initDataSource {
    NSArray *array2 = [[NSMutableArray arrayWithArray:[cityDic allKeys]] sortedArrayUsingSelector:@selector(compare:)];

    _key = [NSMutableArray arrayWithArray:array2];
    CGFloat y = _heartCity.frame.origin.y + CGRectGetHeight(_heartCity.frame);
    CGRect tableRect = CGRectMake(0, y, CGRectGetWidth([RextExtends getScreenFrame]), CGRectGetHeight([RextExtends getScreenFrame]) - y - 64);
    self.tableView = [[UITableView alloc] initWithFrame:tableRect style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.tableFooterView = [UIView new];
     self.tableView.delegate = self;
    [self.view sendSubviewToBack:self.tableView];
    self.tableView.dataSource = self;
    [self.tableView reloadData];
}


- (void)initAbout {
    self.title = @"地区定位";
    _locationRegion.text = [[Common currenCity] customObjectForkey:@"city"];
    // 设置CGRectZero从导航栏下开始计算
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    [self showNavBarWithRightTitle:nil  andRightAction:nil andLeftAction:nil andCustom:NO];
 }


#pragma mark - searchDelegate
//- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
//    searchResults = [[NSMutableArray alloc]init];
//    if (_searchBar.text.length>0&&![ChineseInclude isIncludeChineseInString:_searchBar.text]) {
//        for (int i=0; i<dataArray.count; i++) {
//            if ([ChineseInclude isIncludeChineseInString:[dataArray[i] customObjectForkey:@"NAME"]]) {
//                NSString *tempPinYinStr = [PinYinForObjc chineseConvertToPinYin:[dataArray[i] customObjectForkey:@"NAME"]];
//                NSRange titleResult=[tempPinYinStr rangeOfString:_searchBar.text options:NSCaseInsensitiveSearch];
//                if (titleResult.length>0) {
//                    [searchResults addObject:dataArray[i]];
//                } else {
//                    NSString *tempPinYinHeadStr = [PinYinForObjc chineseConvertToPinYinHead:[dataArray[i] customObjectForkey:@"NAME"]];
//                    NSRange titleHeadResult=[tempPinYinHeadStr
//                                             rangeOfString:_searchBar.text
//                                             options:NSCaseInsensitiveSearch];
//                    if (titleHeadResult.length>0) {
//                        [searchResults addObject:dataArray[i]];
//                    }
//                }
//            }
//            else {
//                NSRange titleResult=[[dataArray[i] customObjectForkey:@"NAME"] rangeOfString:_searchBar.text options:NSCaseInsensitiveSearch];
//                if (titleResult.length>0) {
//                    [searchResults addObject:dataArray[i]];
//                }
//            }
//        }
//    } else if (_searchBar.text.length>0&&[ChineseInclude isIncludeChineseInString:_searchBar.text]) {
//        for (NSDictionary *dic in dataArray) {
//            NSString *tempStr = [dic customObjectForkey:@"NAME"];
//            NSRange titleResult=[tempStr rangeOfString:_searchBar.text options:NSCaseInsensitiveSearch];
//            if (titleResult.length>0) {
//                [searchResults addObject:dic];
//            }
//        }
//    }
//    searchState = YES;
//    [self.view endEditing:YES];
//    [self.tableView reloadData];
//    
//}

#pragma mark - tableView dataSource & delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _key.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *array = [cityDic customObjectForkey:[_key objectAtIndex:section]];
    return array.count == 0 ? 0 : array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    NSArray *array = [cityDic customObjectForkey:[_key objectAtIndex:indexPath.section]];
    cell.textLabel.text = [[array objectAtIndex:indexPath.row] customObjectForkey:@"NAME"];

    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [_key objectAtIndex:section];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     NSArray *array = [cityDic customObjectForkey:[_key objectAtIndex:indexPath.section]];
    //纬度
    NSString *lat = [[array objectAtIndex:indexPath.row] customObjectForkey:@"LAT"];
    NSString *lon = [[array objectAtIndex:indexPath.row] customObjectForkey:@"LON"];
    [self seleteAction:@{@"LAT":lat,@"LON":lon , @"city":[[array objectAtIndex:indexPath.row] customObjectForkey:@"NAME"]}];
 }

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return _key;
}

- (void)currenLocation:(UIGestureRecognizer *)sender {
    //UIView *view = sender.view;
}


- (void)hotCityBtnAction:(UIButton *)sender {
    NSInteger index = sender.tag % 200;
    NSString *lat = [[heartCity objectAtIndex:index] customObjectForkey:@"LAT"];
    NSString *lon = [[heartCity objectAtIndex:index] customObjectForkey:@"LON"];
    [self seleteAction:@{@"LAT":lat,@"LON":lon,@"city":sender.titleLabel.text}];
 }

- (void)seleteAction:(NSDictionary *)Coordinates  {
    if (_target && _action) {
        SuppressPerformSelectorLeakWarning([_target performSelector:_action withObject:Coordinates]);
        [self.navigationController popViewControllerAnimated:YES];

    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
